package cn.bfay.lion.rest;

import cn.bfay.cache.redis.RedisKeyBuilder;
import cn.bfay.cache.redis.RedisTime;
import cn.bfay.cache.redis.RedisUtils;
import cn.bfay.lion.rest.redis.RedisKeyTemplate;
import cn.bfay.wechat.WechatCoreUtil;
import cn.bfay.wechat.model.WechatAccessToken;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 服务启动执行.
 *
 * @author wangjiannan
 */
@RequiredArgsConstructor
@Component
public class StartRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(StartRunner.class);

    @Value("${wechat.debug:false}")
    private boolean wechatDebug;

    private final WechatCoreUtil wechatCoreUtil;

    /**
     * 项目启动第一次加载微信accessToken，后续定时更新accessToken.
     *
     * @param args args
     * @author wangjiannan
     */
    @Override
    public void run(String... args) {
        if (wechatDebug) {
            return;
        }
        while (true) {
            try {
                WechatAccessToken wechatAccessToken = wechatCoreUtil.getAccessToken();
                String redisKey = RedisKeyBuilder.generateRedisKey(RedisKeyTemplate.WECHAT_TOKEN_TEMPLATE);
                RedisUtils.setValue(redisKey, wechatAccessToken.getAccessToken(), RedisTime.HNOUR * 2);
                // 定时
                Thread.sleep((wechatAccessToken.getExpiresIn() - 200) * 1000);
            } catch (Exception e) {
                logger.error("加载微信accessToken异常", e);
                try {
                    Thread.sleep(30 * 1000);// 发生异常休眠30秒
                } catch (Exception e1) {
                    logger.error("", e1);
                }
            }
        }
    }
}

